import Toast from '../miniprogram_npm/@vant/weapp/toast/toast';
import drawQrcode from '../utils/weapp-qrcode-canvas-2d';
var QQMapWX = require('../utils/qqmap-wx-jssdk.js');
var qqmapsdk = new QQMapWX({
  key: require('../env').qqmapKey
});
/**
 * 获取当前日期
 * @param {*} date
 * @returns
 */
const formatDate = date => {
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();

  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  // 获取当前日期
  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':');
};

const formatNumber = n => {
  n = n.toString();
  return n[1] ? n : `0${n}`;
};

/**
 *  错误 消息提示框
 * @param {*} msg  提示的内容
 * @param {*} status 图标
 */
function errorToast(msg, status) {
  Toast.fail(msg);
}

/**
 * 消息提示框
 * @param {*} msg  提示的内容
 * @param {*} status 图标
 */
function showToast(msg, status) {
  wx.showToast({
    title: msg,
    icon: status
  });
}

function isUndefined(T) {
  var res = false;
  if (T == null || T == undefined) {
    res = true;
  }
  return res;
}
/**
 * 判断某一个值是否为空
 * @param {需要判断的值} T
 */
function isEmpty(T) {
  var val = false;
  if (this.isUndefined(T) || T === '') {
    val = true;
  }
  return val;
}

/**
 * 返回某年的当天 YYYY:MM:DD
 * @param {显示当前日期} M
 * @returns
 */
function nowDate(M) {
  var dates = new Date();
  var year = dates.getFullYear();
  var Years = year + M;
  var math = dates.getMonth() + 1;
  var day = dates.getDate();
  return Years + '-' + math + '-' + day;
}

/**
 *  正数表示之后的时间
 * 负数表示之前的时间
 * 0表示当天
 * @param {*} num
 */
function fun_data(num) {
  var date1 = new Date();
  var date2 = new Date(date1);
  date2.setDate(date1.getDate() + num);
  return date2.getFullYear() + '-' + (date2.getMonth() + 1) + '-' + date2.getDate();
}

/**
 * 获取当前时间
 * @returns
 */
function nowTime() {
  var date = new Date();
  const hour = date.getHours();
  const minute = date.getMinutes();
  // const second = date.getSeconds()

  return hour + ':' + minute;
}
/**
 * 防抖
 * callBack回调函数里面如果要使用this不要用箭头函数
 */
function debounce(callBack, time) {
  var timer = null;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      callBack.call(this, ...args);
    }, time);
  };
}

/**
 * 节流
 * callBack回调函数里面如果要使用this不要用箭头函数
 */

function throttle(callBack, time) {
  var flag = true;
  return function (...args) {
    if (flag) {
      setTimeout(() => {
        callBack.call(this, ...args);
        flag = true;
      }, time);
    }
    flag = false;
  };
}
// 获取定位
function initGetLocationFlunction() {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      success: res => {
        resolve(res.result);
      },
      fail: function (res) {
        console.log(res, 11);
        reject('定位失败');
      }
    });
  });
}
//封装定位方法
function initLocationPersmiss() {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: res => {
        // res.authSetting['scope.userLocation'] == undefined  表示 初始化进入该页面
        // res.authSetting['scope.userLocation'] == false  表示 非初始化进入该页面,且未授权
        // res.authSetting['scope.userLocation'] == true  表示 地理位置授权
        if (res.authSetting['scope.userLocation'] != undefined && res.authSetting['scope.userLocation'] != true) {
          未授权;
          wx.showModal({
            title: '请求授权当前位置',
            content: '需要获取您的地理位置，请确认授权',
            success: function (res) {
              if (res.cancel) {
                //取消授权
                wx.showToast({
                  title: '拒绝授权 暂时无法使用本功能',
                  icon: 'none',
                  duration: 1000
                });
                reject('定位失败');
              } else if (res.confirm) {
                //确定授权，通过wx.openSetting发起授权请求
                wx.openSetting({
                  success: function (res) {
                    if (res.authSetting['scope.userLocation'] == true) {
                      wx.showToast({
                        title: '授权成功',
                        icon: 'success',
                        duration: 1000
                      });
                      //再次授权，调用wx.getLocation的API
                      resolve(initGetLocationFlunction());
                    } else {
                      wx.showToast({
                        title: '授权失败',
                        icon: 'none',
                        duration: 1000,
                        mask: true
                      });
                      reject('定位失败');
                    }
                  }
                });
              }
            }
          });
        } else if (res.authSetting['scope.userLocation'] == undefined || res.authSetting['scope.userLocation']) {
          //用户首次进入页面,调用wx.getLocation的API
          resolve(initGetLocationFlunction());
        } else {
          reject('错误');
        }
      }
    });
  });
}
// 判断用户某个权限是否弹起过
function judgeAuth(auth) {
  return new Promise((resolve, reject) => {
    wx.getSetting({
      success: res => {
        resolve(res.authSetting[auth]);
      }
    });
  });
}
//打开授权列表
function openAuth(auth) {
  return new Promise((resolve, reject) => {
    wx.openSetting({
      success: res => {
        resolve(res.authSetting[auth]);
      }
    });
  });
}
/**
 * 地址解析，通过地址获取经纬度
 * @param {string} address
 */
function getLatLng(address) {
  return new Promise((resolve, reject) => {
    qqmapsdk.geocoder({
      address: address,
      success: res => {
        resolve(res.result);
      }
    });
  });
}
/**
 * 逆转地址解析，通过经纬度获取地址
 * @param {number} latitude -纬度
 * @param {string} longitude -经度
 */
function getAddress(latitude, longitude) {
  return new Promise((resolve, reject) => {
    qqmapsdk.reverseGeocoder({
      location: {
        latitude,
        longitude
      },
      success: res => {
        resolve(res.result);
      },
      fail: err => {
        reject(err);
      }
    });
  });
}
/**
 * @return {number}
 */
function getDistance(from, to) {
  return new Promise((resolve, reject) => {
    qqmapsdk.calculateDistance({
      from: from,
      to: [to],
      success: res => {
        resolve(res.result.elements[0]);
      },
      fail: err => {
        reject(new Error(err));
      }
    });
  });
}
/**
 *  连接wifi操作
 */
function connectOperaiton(systemInfo, account, password) {
  return new Promise((resolve, reject) => {
    const { system, platform } = systemInfo;
    console.log(system, platform, system.substr(8));
    if ((platform == 'android' && system.substr(8) > 6) || (platform == 'ios' && system.substr(4) > 11)) {
      wx.startWifi({
        success: () => {
          wx.connectWifi({
            forceNewApi: true,
            SSID: account,
            password: password,
            success: () => {
              if (platform == 'iso') {
                wx.onWifiConnected(function (res) {
                  if (res.wifi.SSID == account) {
                    wx.showToast({
                      title: 'wifi连接成功',
                      icon: 'success'
                    });
                    resolve();
                  } else {
                    wx.showToast({
                      title: 'wifi连接失败',
                      icon: 'error'
                    });
                    reject();
                  }
                });
                return;
              }
              wx.showToast({
                title: 'wifi连接成功',
                icon: 'success'
              });
              resolve();
            },
            fail: err => {
              console.log(err, 'wifi连接失败');
              let errCode = err.errCode;
              let msg = 'wifi连接失败';
              if (platform == 'android') {
                if (errCode == 12005) msg = '未打开wifi开关';
              }
              wx.showToast({
                title: msg,
                icon: 'error'
              });
              reject();
            }
          });
        },
        fail: err => {
          console.log(err, 'wifi初始化失败');
          let errCode = err.errCode;
          let msg = 'wifi初始化失败';
          if (platform == 'android') {
            if (errCode == 12005) msg = '未打开wifi开关';
          }
          wx.showToast({
            title: msg,
            icon: 'error'
          });
          reject();
        }
      });
    } else {
      wx.showToast({
        title: '设备不支持',
        icon: 'error'
      });
      reject();
    }
  });
}

/**
 *  @descprition 连接wifi
 */

function connectWifi(account, passowrd) {
  wx.showToast({
    title: '连接wifi打开中',
    icon: 'loading',
    mask: true
  });
  return new Promise(resolve => {
    const { systemInfo } = getApp().globalData;
    if (systemInfo) {
      resolve(connectOperaiton(systemInfo, account, passowrd));
    } else {
      app.connectWifi = function () {
        resolve(connectOperaiton(getApp().globalData.systemInfo, account, passowrd));
      };
    }
  });
}
/**
 * 一维数组变为二维数组
 * @param {array} arr
 * @param {number} size
 * @return {array}
 */
function arrToTwoArr(arr, size) {
  size = Number(size);
  let tempArr = [];
  let length = arr.length;
  if (length <= size) return [arr];
  let index = 0;
  let arrNum = Math.ceil(length / size);
  for (let i = 0; i < arrNum; i++) {
    tempArr[i] = [];
    let end = index + size < length ? index + size : length;
    let tempIndex = index;
    for (let j = tempIndex; j < end; j++) {
      tempArr[i].push(arr[j]);
      index++;
    }
  }
  return tempArr;
}
function formatTime(date, type = 'datetime') {
  date = new Date(date);
  const year = date.getFullYear();
  const month = date.getMonth() + 1;
  const day = date.getDate();
  const hour = date.getHours();
  const minute = date.getMinutes();
  const second = date.getSeconds();
  if (type == 'year-month') {
    return `${[year, month].map(formatNumber).join('-')}`;
  } else if (type == 'datetime') {
    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute].map(formatNumber).join(':')}`;
  } else if (type === 'date') {
    return `${[year, month, day].map(formatNumber).join('-')}`;
  } else if (type === 'time') {
    return `${[hour, minute, second].map(formatNumber).join(':')}`;
  } else if ((type = 'all')) {
    return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute, second].map(formatNumber).join(':')}`;
  }
}
/**
 * @description {日期字符串变为日期对象}
 * @param {yyy-mm-dd hh:mm}
 */
function getDatetime(datetime) {
  let val = datetime.split(' ');
  let date = val[0].split('-');
  let time = val[1] ? val[1].split(':') : [];
  let year = parseInt(date[0]);
  let month = parseInt(date[1]) - 1;
  let day = parseInt(date[2]);
  let hour = parseInt(time[0]);
  let minute = parseInt(time[1]);
  if (time[2]) {
    return new Date(year, month, day, hour, minute, parseInt(time[2]));
  } else if (time[1]) {
    return new Date(year, month, day, hour, minute);
  } else {
    return new Date(year, month, day);
  }
}
/**
 * @description 格式化时间为字符串
 */
function formatDateString(date, format = 'yyyy-MM-dd HH:mm:ss') {
  if (typeof date === 'number') date = new Date(date);
  if (date instanceof Date) {
    const year = date.getFullYear().toString();
    const month = (date.getMonth() + 1).toString();
    const month2 = month.length > 1 ? month : '0' + month;
    const day = date.getDate().toString();
    const day2 = day.length > 1 ? day : '0' + day;
    const hours = date.getHours().toString();
    const hours2 = hours.length > 1 ? hours : '0' + hours;
    const minutes = date.getMinutes().toString();
    const minutes2 = minutes.length > 1 ? minutes : '0' + minutes;
    const seconds = date.getSeconds().toString();
    const seconds2 = seconds.length > 1 ? seconds : '0' + seconds;

    return format
      .replace('yyyy', year)
      .replace('MM', month2)
      .replace('M', month)
      .replace('dd', day2)
      .replace('d', day)
      .replace('HH', hours2)
      .replace('H', hours)
      .replace('mm', minutes2)
      .replace('m', minutes)
      .replace('ss', seconds2)
      .replace('s', seconds);
  }
}
/**
 * @description 时间如果再今天或者明天就不显示年月日
 */
function getOptimizeDate(date) {
  if (typeof date === 'string' || typeof date === 'number') date = new Date(date);
  if (!(date instanceof Date)) return;
  let hours = date.getHours();
  hours < 10 && (hours = '0' + hours);
  let minutes = date.getMinutes();
  minutes < 10 && (minutes = '0' + minutes);
  date = date.getTime();
  let str = '';
  const nowDate = new Date();
  nowDate.setHours(0);
  nowDate.setMinutes(0);
  nowDate.setSeconds(0);
  const todayStart = new Date(nowDate).getTime();
  const todayEnd = todayStart + 24 * 60 * 59 * 1000;
  const tomorrowStart = todayEnd + 1000;
  const tomorrowEnd = tomorrowStart + 24 * 60 * 59 * 1000;
  if (date >= todayStart && date <= tomorrowEnd) {
    str = (date >= todayStart && date <= todayEnd ? '今天 ' : '明天 ') + hours + ':' + minutes;
  } else {
    str = formatDateString(date, 'yyyy年MM月dd日 HH:mm');
  }
  return str;
}
/**
 *  @description 对时间段进行操作
 */
function getOptimizeDateTwo(date) {
  if (date.includes('~')) {
    date = date.split('~');
    let temp = getOptimizeDate(date[1]).replace(/今天|明天|.*日/, '');
    return getOptimizeDate(date[0]) + '~' + temp;
  } else {
    return getOptimizeDate(date);
  }
}

/**
 * @description {深度克隆}
 * @param {*} obj
 */

function deepClone(obj) {
  let newObj = Array.isArray(obj) ? [] : {};
  if (obj && typeof obj === 'object') {
    for (let key in obj) {
      if (obj.hasOwnProperty(key)) {
        newObj[key] = obj && typeof obj[key] === 'object' ? deepClone(obj[key]) : obj[key];
      }
    }
  }
  return newObj;
}

/**
 *  获取元素
 */

function getElement(el) {
  return new Promise((resovle, reject) => {
    const query = wx.createSelectorQuery();
    query.select(el).boundingClientRect();
    query.exec(res => {
      resovle(res.map(item => item));
    });
  });
}

/**
 *  获取多个相同的元素
 */
function getElements(el) {
  return new Promise((resovle, reject) => {
    const query = wx.createSelectorQuery();
    query.selectAll(el).boundingClientRect();
    query.exec(res => {
      resovle(res.map(item => item));
    });
  });
}

/**
 * 获取多个不同元素
 */
function getElementDs(els) {
  const arr = [];
  els.forEach(el => {
    const obj = new Promise((resovle, reject) => {
      const query = wx.createSelectorQuery();
      query.select(el).boundingClientRect();
      query.exec(res => {
        resovle(...res.flat());
      });
    });
    arr.push(obj);
  });

  return Promise.all(arr);
}
function getQrcode(el, content) {
  return new Promise((resolve, reject) => {
    const query = wx.createSelectorQuery();
    query
      .select(el)
      .fields({
        node: true,
        size: true
      })
      .exec(res => {
        var canvas = res[0].node;
        // 调用方法drawQrcode生成二维码
        drawQrcode({
          canvas: canvas,
          canvasId: el,
          width: 260,
          padding: 30,
          background: '#ffffff',
          foreground: '#000000',
          text: content
        });
        // 获取临时路径（得到之后，想干嘛就干嘛了）
        wx.canvasToTempFilePath({
          canvasId: el,
          canvas: canvas,
          x: 0,
          y: 0,
          width: 260,
          height: 260,
          destWidth: 260,
          destHeight: 260,
          success(res) {
            // console.log('二维码临时路径：', res.tempFilePath)
            resolve(res.tempFilePath);
          },
          fail(res) {
            console.error(res);
          }
        });
      });
  });
}
/**
 *  @description 复制相同的属性
 */
function bindProps(target, obj) {
  Object.keys(target).forEach(item => {
    if (obj.hasOwnProperty(item)) {
      target[item] = obj[item];
    }
  });
}
/**
 * 选择图片
 */

function selectImg() {
  return new Promise((resolve, rejcet) => {
    wx.chooseMedia({
      mediaType: 'image',
      sourceType: ['album', 'camera'],
      success: res => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        wx.getFileSystemManager().readFile({
          filePath: tempFilePath,
          encoding: 'base64',
          success: res => {
            // 这里再次给赋值，因为没有调用setData所以不会影响页面变化
            const params = {
              tempPath: tempFilePath,
              baseCode: res.data
            };
            resolve(params);
          }
        });
      }
    });
  });
}
/**
 * 解决录音组件在各个页面使用的bug
 */
function recordSoundCpn() {
  const pages = getCurrentPages().filter(item => {
    return item.route == 'pages/home/index' || item.route == 'subcontract/home/pages/goodsList/index';
  });
  if (pages.length) {
    pages.forEach(page => {
      page.setData({
        showSoundCop: false
      });
    });
  }
}
function validate(arr, data) {
  return !arr.find(item => {
    const val = data[item.key];
    if (!val) {
      Toast.fail(item.msg);
      return true;
    } else if (item.pattern) {
      const val2 = item.pattern.find(item2 => !item2.reg.test(val));
      if (val2) {
        Toast.fail(val2.msg);
        return true;
      }
    }
  });
}

/**
 *  获取一个随机数,通过时间戳与随机数
 */
function getRandom() {
  return Number(Math.random().toString() + Date.now()).toString(36);
}
/**
 *  获取整数倍时间
 */
function getMinuteIntTime(minutes) {
  let maxHours = 0;
  let timeList = [];
  do {
    const val = maxHours > 9 ? '' + maxHours : '0' + maxHours;
    let maxMinutes = 0;
    do {
      let val2 = maxMinutes > 9 ? '' + maxMinutes : '0' + maxMinutes;
      val2 = val + ':' + val2;
      timeList.push(val2);
      maxMinutes = maxMinutes + minutes;
    } while (maxMinutes < 60);
    maxHours++;
  } while (maxHours < 24);
  return timeList;
}

/**
 * 获取树中的某个节点
 * @param {array} arr 需要遍历的树数组
 * @param val 判断是否相等的值
 * @param prop 属性名默认是id
 */

function getNode(arr, val, prop = 'id') {
  let target = null;
  arr.find(item => {
    if (item[prop] == val) {
      target = item;
      return true;
    } else if (item.children) {
      return (target = getNode(item.children, val));
    }
  });
  return target;
}
function getAgeByIdCard(userCard, num = 3) {
  //获取出生日期
  var birth;
  if (num == 1) {
    birth = userCard.substring(6, 10) + '-' + userCard.substring(10, 12) + '-' + userCard.substring(12, 14);
    return birth;
  }
  //获取性别
  if (num == 2) {
    if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
      return '男';
    } else {
      return '女';
    }
  }
  //获取年龄
  if (num == 3) {
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var day = myDate.getDate();
    var age = myDate.getFullYear() - userCard.substring(6, 10) - 1;
    if (
      userCard.substring(10, 12) < month ||
      (userCard.substring(10, 12) == month && userCard.substring(12, 14) <= day)
    ) {
      age++;
    }
    return age;
  }
}
/**
 *
 * @param {number} number 生成随机数的个数
 */
function makeRandom(number) {
  const chars = [
    '0',
    '1',
    '2',
    '3',
    '4',
    '5',
    '6',
    '7',
    '8',
    '9',
    'A',
    'B',
    'C',
    'D',
    'E',
    'F',
    'G',
    'H',
    'I',
    'J',
    'K',
    'L',
    'M',
    'N',
    'O',
    'P',
    'Q',
    'R',
    'S',
    'T',
    'U',
    'V',
    'W',
    'X',
    'Y',
    'Z',
    'a',
    'b',
    'c',
    'd',
    'e',
    'f',
    'g',
    'h',
    'i',
    'j',
    'k',
    'l',
    'm',
    'n',
    'o',
    'p',
    'q',
    'r',
    's',
    't',
    'u',
    'v',
    'w',
    'x',
    'y',
    'z'
  ];
  let nums = '';
  for (var i = 0; i < number; i++) {
    var id = parseInt(Math.random() * 61);
    nums += chars[id];
  }
  return nums;
}
// 时间戳 返回 UTC yymmss
const getHourMiSe = time => {
  // console.log(time)
  const data = new Date(time);
  // console.log('data',data)
  const h = data.getUTCHours();
  const m = data.getUTCMinutes();
  const s = data.getUTCSeconds();
  return `${h < 10 ? '0' + h : h}:${m < 10 ? '0' + m : m}:${s < 10 ? '0' + s : s}`;
};
/**
 * 修改数字为中文
 */
const numToText = type => {
  switch (type) {
    case 1:
      return '一';
    case 2:
      return '二';
    case 3:
      return '三';
    case 4:
      return '四';
    case 5:
      return '五';
    case 6:
      return '六';
    case 7:
      return '七';
    case 8:
      return '八';
    case 9:
      return '九';
    case 10:
      return '十';
  }
};
/**
 * 获取几天内的格式化日期
 */
var getFormatDays = days => {
  const nowDate = new Date();
  const stamp = nowDate.getTime();
  const arr = [];
  for (let i = 0, j = days; i < j; i++) {
    let name = '今天';
    let date = formatDateString(stamp, 'yyyy-MM-dd');
    let id = date.split('-').at(-1);
    if (i == 1) {
      date = formatDateString(stamp + 24 * 60 * 60 * 1000, 'yyyy-MM-dd');
      id = date.split('-').at(-1);
      name = '明天';
    } else if (i > 1) {
      date = formatDateString(stamp + 24 * 60 * 60 * 1000 * i, 'yyyy-MM-dd');
      id = date.split('-').at(-1);
      name = id + '号';
    }
    arr.push({
      id,
      name,
      date
    });
  }
  return arr;
};
/**
 * 判断时分的大小,返回值为1表示time1大 为0表示相等 -1表示time2大
 */
var compareTime = (time1, time2) => {
  let time1List = time1.split(':').map(item => Number(item));
  let time2List = time2.split(':').map(item => Number(item));
  if (time1List[0] > time2List[0] || (time1List[0] === time2List[0] && time1List[1] > time2List[1])) return 1;
  if (time1List[0] === time2List[0] && time1List[1] === time2List[1]) return 0;
  return -1;
};

var joinUrl = function (baseUrl, path) {
  // 如果基础 URL 以斜杠结尾，且路径以斜杠开头，则去除其中一个斜杠
  if (baseUrl.endsWith('/') && path.startsWith('/')) {
    return baseUrl + path.substring(1);
  }
  // 如果基础 URL 不以斜杠结尾，且路径不以斜杠开头，则添加斜杠
  if (!baseUrl.endsWith('/') && !path.startsWith('/')) {
    return baseUrl + '/' + path;
  }
  // 其他情况直接拼接
  return baseUrl + path;
};

/**
 *  在树中通过值或者属性是否相等获取对应的节点列表
 */
var filterTreeToArr = function (arr, target, prop = null, tempArr = []) {
  let res = [];
  arr.find(item => {
    let tempArr2 = [...tempArr, item];
    if ((prop && item[prop] == target[prop]) || (!prop && item == target)) {
      return (res = tempArr2);
    }
    if (item.children) {
      res = filterTreeToArr(item.children, target, prop, tempArr2);
      return res.length > 0;
    }
  });
  return res;
};

/**
 * 删除空的子节点
 */
var deEmptyChildren = function (arr) {
  arr.forEach(item => {
    if (!item.children) return;
    if (!item.children.length) return Reflect.deleteProperty(item, 'children');
    this.deEmptyChildren(item.children);
  });
};
/**
 * 判断当前时间是否在时间之内
 */
module.exports = {
  formatTime,
  formatDate,
  formatDateString,
  errorToast,
  showToast,
  isEmpty,
  isUndefined,
  nowDate,
  nowTime,
  fun_data,
  debounce,
  throttle,
  getLatLng,
  getAddress,
  initLocationPersmiss,
  initGetLocationFlunction,
  getDistance,
  arrToTwoArr,
  deepClone,
  getDatetime,
  getElement,
  getElements,
  getElementDs,
  getQrcode,
  bindProps,
  connectWifi,
  selectImg,
  recordSoundCpn,
  validate,
  judgeAuth,
  openAuth,
  getRandom,
  getOptimizeDate,
  getMinuteIntTime,
  getOptimizeDateTwo,
  getNode,
  getAgeByIdCard,
  makeRandom,
  getHourMiSe,
  numToText,
  getFormatDays,
  compareTime,
  joinUrl,
  filterTreeToArr,
  deEmptyChildren
};
